package com.zlz.open.ugs.exchange.request;

import com.zlz.open.ugs.common.config.exception.ExceptionCode;
import com.zlz.open.ugs.exception.pre.UGSPrePostException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: zhulinzhong
 * @Date: 2024/6/3
 */
@Slf4j
@Data
public class RequestBody {

    private UgsRequest request;

    private byte[] body;

    public RequestBody() {
    }

    public RequestBody(byte[] body, UgsRequest request) {
        this.body = body;
        this.request = request;
    }

    public String toString() {
        try {
            String encodingType = request.getUrl().getEncodingType();
            return new String(body, encodingType);
        } catch (Exception e) {
            log.error("body解析失败", e);
            throw new UGSPrePostException(ExceptionCode.BODY_SERIALIZATION_FAIL);
        }
    }

    public byte[] toBytes(String data) {
        try {
            return data.getBytes(request.getUrl().getEncodingType());
        } catch (Exception e) {
            log.error("body解析失败", e);
            throw new UGSPrePostException(ExceptionCode.BODY_SERIALIZATION_FAIL);
        }
    }

    public void shift(String contentType, String filename, String data) {
        request.setBody(new FileRequestBody(contentType, toBytes(data), request, filename));
    }
}
